const { Router } = require("express");
const JWT = require("jsonwebtoken");
const User = require("../model/User");
const Cart = require("../model/Cart");

const router = new Router();

// 登录了才能操作
// 中间件，用于处理是否登录了，设置了一道令牌
router.use(async (req, res, next) => {
    try {
        const token = req.headers["authorization"].replace("Bearer ", "");
        const result = JWT.verify(token, "hello world");
        const user = await User.findById(result._id);
        if (user) {
            req.userInfo = user;
            next();
        } else {
             res.json({ code: -1, message: "请重新登录" });
        }
    } catch (error) {
        console.log(error);
        throw new Error("用户不存在");
    }
});

// 添加商品进入购物车
router.post("/add_goods", async (req, res) => {
    const {
        goodsId,
        count,
        name,
        picUrl,
        selected,
        counterPrice,
        retailPrice,
    } = req.fetchBody;
    const selectedIDs = selected.map((item) => item.id).join(";");
    //   查询数据库中是否有该数据
    const cartData = await Cart.findOne({
        user: req.userInfo,
        goodsID: goodsId,
        selectedIDs,
    });
    console.log(cartData);
    if (cartData) {
        // 修改数量
        await Cart.updateOne(
            {
                user: req.userInfo,
                goodsID: goodsId,
                selectedIDs,
            },
            {
                count: cartData.count + count,
            }
        );
    } else {
        await new Cart({
            goodsID: goodsId,
            goodsName: name,
            goodsImg: picUrl,
            user: req.userInfo._id,
            count,
            selected,
            selectedIDs,
            counterPrice,
            retailPrice,
        }).save();
    }
    res.json({ code: 0, message: "ok" });
});
// 查询用户的所有购物车商品
router.get("/get_cart_goods", async (req, res) => {
    const result = await Cart.find({ user: req.userInfo._id });
    res.json({ code: 0, message: "ok", data: result });
});

router.post("/modify_goods", async (req, res) => {
    const { id, ...rest } = req.fetchBody;
    const result = await Cart.updateOne({ _id: id }, rest);
    if (result.nModified) {
        res.json({ code: 0, message: "ok" });
    } else {
        res.json({ code: -1, message: "更新失败" });
    }
});
router.post("/modify_goods_checked", async (req, res) => {
    const {...rest } = req.fetchBody;
    const data = await Cart.find({ user: req.userInfo._id })
    data.forEach(async(item)=>{
        await Cart.updateOne({ _id: item._id }, rest)
    })
    const result = await Cart.find({ user: req.userInfo._id });
    res.json({ code: 0, message: "ok", data: result });
});
module.exports = router;
